package com.ds.infra.rpc.core.transport.client;

import com.ds.infra.rpc.core.cache.RpcResponseCache;
import com.ds.infra.rpc.core.protocol.RpcProtocol;
import com.ds.infra.rpc.core.protocol.RpcRequest;
import com.ds.infra.rpc.core.protocol.RpcResponse;
import com.ds.infra.rpc.core.transport.client.handler.RpcResponseHandler;
import com.ds.infra.rpc.core.transport.codec.RpcDecoder;
import com.ds.infra.rpc.core.transport.codec.RpcEncoder;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.DisposableBean;

import java.util.concurrent.CompletableFuture;

/**
 * Netty客户端实现
 * 关键功能：
 * 1. 连接管理（自动重连）
 * 2. 请求分发
 * 3. 资源清理
 *
 * @author WeiShaoying
 */
@Slf4j
public class NettyClient implements RpcClient, DisposableBean {

    private final EventLoopGroup workerGroup;
    private final Bootstrap bootstrap;
    private final String host;
    private final int port;
    private volatile Channel channel;

    public NettyClient(String host, int port) {
        this.host = host;
        this.port = port;
        this.workerGroup = new NioEventLoopGroup();
        this.bootstrap = new Bootstrap();
        initBootstrap();
    }

    private void initBootstrap() {
        bootstrap.group(workerGroup)
                .channel(NioSocketChannel.class)
                .option(ChannelOption.TCP_NODELAY, true)
                .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 5000)
                .handler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel ch) {
                        ch.pipeline()
                                // 解决粘包/半包（配置同服务端）
                                .addLast(new LengthFieldBasedFrameDecoder(1024 * 1024, 4, 4, 0, 0))
                                // 解码为RpcResponse
                                .addLast(new RpcDecoder<>(RpcResponse.class))
                                // 编码RpcRequest
                                .addLast(new RpcEncoder<>(RpcRequest.class))
                                // 必须使用RpcResponseHandler（处理服务端返回的响应）
                                .addLast(new RpcResponseHandler());
                    }
                });
    }

    @Override
    public CompletableFuture<RpcResponse> send(RpcProtocol<RpcRequest> protocol) {
        log.info("====> NettyClient 准备发送: {}", protocol);
        // 确保连接已建立
        if (channel == null || !channel.isActive()) {
            synchronized (this) {
                if (channel == null || !channel.isActive()) {
                    // 尝试建立连接
                    connect();
                }
            }
        }
        CompletableFuture<RpcResponse> future = new CompletableFuture<>();
        RpcResponseCache.put(protocol.getBody().getRequestId(), future);

        channel.writeAndFlush(protocol).addListener((ChannelFutureListener) channelFutureListener -> {
            if (!channelFutureListener.isSuccess()) {
                future.completeExceptionally(channelFutureListener.cause());
                log.error("Send request failed", channelFutureListener.cause());
            }
        });
        log.info("====> NettyClient 发送完毕: {}", protocol);
        return future;
    }

    public void connect() {
        try {
            ChannelFuture future = bootstrap.connect(host, port).sync();
            this.channel = future.channel();
            channel.closeFuture().addListener(f -> log.info("Connection closed"));
            log.info("====Connected to server {}:{}", host, port);
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
            throw new RuntimeException("Connection interrupted", e);
        }
    }

    public void reconnect() {
        if (channel != null) {
            channel.close();
        }
        log.info("Attempting to reconnect...");
        connect(); // 复用原有连接逻辑
    }

    @Override
    public void shutdown() {
        if (channel != null) {
            channel.close();
        }
        workerGroup.shutdownGracefully();
        log.info("Netty client resources released");
    }

    @Override
    public void destroy() {
        shutdown();
    }
}
